const _ = require('lodash');
const {readDir, isDir} = require('./utils/dir');

const routeMap = [];

const options = {
  excludes: [/node_modules/, isJsFile],
  recursion: true,
  onlyFile: true,
};

/**
 * 是否js 文件
 * @param file
 * @returns {boolean}
 */
function isJsFile(file) {
  return !isDir(file) && !/(\.js|\.ts|\.jsx)$/.test(file);
}

// 路由加载器
class RouterLoader {

  constructor(app, dirs = []) {
    if (_.isArray(dirs)) {
      this.dirs = dirs;
    }
    if (_.isString(dirs)) {
      this.dirs = [dirs]
    }
    if (_.isObject(app) && app !== undefined) {
      this.app = app
    }
    this.option = options;
    this.loads();
  }

  loads(force) {
    if (0 < routeMap.length && true !== force) {
      return
    }
    this.dirs.forEach((dir, _index) => {
      this.routeMap(readDir(dir, this.options()), this.app)
    });
  }

  routeMap(routes, app) {

    if (!_.isObject(app) || _.isEmpty(routes) || !_.isFunction(app.use)) {
      return false;
    }
    routes.forEach((routeFile, _index) => {
      let controllerFile = this.file(routeFile);
      let {controller, path, prefix} = require(controllerFile);
      // 非 controller
      if (_.isUndefined(controller) || _.isUndefined(path)) {
        return;
      }
      let api = _.replace(prefix + path, '//', '/');
      let item = {
        api,
        controllerFile,
        prefix, path,
        controller,
      };
      // 已经加载过
      if (routeMap.includes(item)) {
        return
      }
      if (!_.isNil(controller) && !_.isEmpty(path) && _.isString(path)) {
        app.use(path, controller);
        // 载入缓存记录
        routeMap.push(item)
      }
    });
  }

  options() {
    return this.option
  }

  file(path) {
    return _.replace(path, '.js', '')
  }

  debug() {
    console.log(this.map())
  }

  map() {
    return routeMap
  }

}

module.exports = RouterLoader;

